package com.czk.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * bio服务器验证
 *
 * @Author:ChenZhangKun
 * @Date: 2021/1/10 21:03
 */
public class BioServer {
    public static void main(String[] args) throws IOException {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        // 创建serverSocket
        ServerSocket serverSocket=new ServerSocket(6666);
        System.out.println("服务器启动了");
        while (true){
            // 监听客户端
            System.out.println("等待链接");
            Socket socket = serverSocket.accept();
            System.out.println("连接到客户端");
            // 创建一个线程与之通讯
            // bio每一个连接都会新建线程，导致客户端比较多时服务器线程开销很大，严重限制了服务器的性能
            threadPool.execute(()->{
                // 与客户端通讯
                try {
                    handler(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }
    public static void handler(Socket socket) throws IOException {
        try {
            System.out.println(Thread.currentThread().getName());
            byte[] bytes=new byte[1024];
            // 通过socket获取输入流
            InputStream inputStream = socket.getInputStream();
            while (true){
                // 没有数据发送或阻塞在此
                System.out.println("等待输入");
                int read = inputStream.read(bytes);
                if (read!=-1){
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        }catch (Exception ex){

        }finally {
            socket.close();
        }
    }
}
